
var api = require('../../utils/api.js');
var app = getApp();
//let innerAudioContext = ''
//let bgAudioMannager = ''
Page({

  /**
   * 页面的初始数据
   */
  data: {
    idx: '',
    audioList:[],
    audioWay: 0,//播放方式 0顺序播放 1随机播放 2单曲循环
    playState: 0,//播放状态
    musicValue: 0,
    nowmiao: 0,//当前时间
    allmiao: 0,//全部时间
    // isFocus:false,
    keywords:'',
    isHidden:false,
    midx:''
  },
  // checkFocus(){
  //   this.setData({
  //     isFocus: true
  //   })
  // },
  // lowFocus(){
  //   this.setData({
  //     isFocus: false
  //   })
  // },
  
  optMusic(e){
    wx.showActionSheet({
      itemList: ['移出歌单'],
      itemColor:'#BA5C5C',
      success:(res)=> {
        if (res.tapIndex==0){
          var id = e.currentTarget.dataset.id;
          api.fetchApi('music/join_the_playlist', { type: 2, id, token: wx.getStorageSync('token') }).then(res => {
            wx.showToast({
              title: '取消收藏'
            })
            this.getMusicList(this.data.keywords,1,null,0);
           
            console.log(this.data.audioList[this.data.idx])
            if (this.data.audioList[this.data.idx].music_id==id){
              this.setData({
                playState: 0
              })
              wx.getBackgroundAudioManager().stop();
             
             
            }
           
          })
        }
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },


  //搜索
  searchMusic(e) {
    this.setData({
      keywords: e.detail.value
    })
   
  },
  search1(e) {
    this.setData({
      // audioList:[],
      keywords: e.detail.value,
      // isFocus:false
    })

    this.getMusicList(this.data.keywords, 1,null,0)
  },

//我的歌单
  getMusicList(search, page, type = null, isSearch=1){
    var nowMusic = this.data.audioList[this.data.idx] || wx.getStorageSync('nowMusic1');
    wx.setStorageSync('nowMusic1', nowMusic)
    console.log(nowMusic)
    this.setData({
      nowMusic
    })
    api.fetchApi('music/my_music_list', { page, search, token: wx.getStorageSync('token'),type }).then(res=>{
      var audioList = this.data.audioList,
        audioList1 = res;
      console.log(audioList1)
      if (audioList1.length == 0 && page > 1) {
        return
      }
      page == 1 ? audioList = res : audioList = [...audioList, ...audioList1]
      if (audioList.length == 0) {
       
        console.log(nowMusic)
        this.setData({
          nowMusic
        })
      //     innerAudioContext.destroy()
      // innerAudioContext = ''
        // return
      }
      this.setData({
        audioList,
        page
      })
      var itemIndex = this.data.audioList.findIndex((item) => item.id == wx.getStorageSync('nowMusic1').id)
      console.log(itemIndex)
      itemIndex < 0 ? itemIndex = '' : ''
      this.setData({
        idx: itemIndex
      })

        if (isSearch == 1) {
        
        this.audioInit1();
      }
    })
  },


  audioInit1() {
    var bgAudioMannager = wx.getBackgroundAudioManager();
    if (this.data.idx !== '') {
      var nowMusic = this.data.audioList[this.data.idx];
      wx.setStorageSync('nowMusic1', nowMusic)
      this.setData({
        nowMusic
      })

    } else {
      return
    }

    console.log(bgAudioMannager.currentTime, '前')
    var that = this
    bgAudioMannager.title = this.data.audioList[this.data.idx].name;
    bgAudioMannager.singer = this.data.audioList[this.data.idx].singer;
    bgAudioMannager.coverImgUrl = this.data.audioList[this.data.idx].cover;
    bgAudioMannager.src = this.data.audioList[this.data.idx].src;

    this.nonitor()

  },

  //监听音乐状态
  nonitor() {
    let bgAudioMannager = wx.getBackgroundAudioManager();
    bgAudioMannager.onPlay(() => {
      console.log('播放')
      this.playFunc()
    })
    bgAudioMannager.onPause(() => {
      console.log('暂停')
      this.pauseFunc()
    })
    bgAudioMannager.onEnded(() => {
      this.nextPlay()
    })
    bgAudioMannager.onTimeUpdate(() => {
      //console.log(bgAudioMannager.currentTime, 'onTimeUpdate')
      this.setData({
        nowmiao: Math.floor(bgAudioMannager.currentTime),
        allmiao: Math.floor(bgAudioMannager.duration),
        isHidden: true
      })

    })
  },



  pauseMusic() {
    console.log(this.data.playState)
    if (this.data.playState == 1) {
      //暂停
      wx.getBackgroundAudioManager().pause()
    } else {
      //播放
      if (wx.getBackgroundAudioManager().src == undefined) {
        this.audioInit1()
      }
      wx.getBackgroundAudioManager().play()

    }


  },

  playMusic(e) {
    var idx = e.currentTarget.dataset.idx;
    this.setData({
      idx,
      musicValue: 0,
      isHidden:true
    })

    var nowMusic = this.data.audioList[this.data.idx] || wx.getStorageSync('nowMusic1');
    console.log(nowMusic)
    wx.setStorageSync('nowMusic1', nowMusic)
    this.setData({
      nowMusic
    })
    // this.setData({
    //  // isPause: false
    //   playState: 1
    // })
    this.audioInit1();

  },


  //拖动快进
  sliderChange(e) {
    this.setData({
      nowmiao: e.detail.value
    })
    wx.getBackgroundAudioManager().seek(this.data.nowmiao)
  },
  playFunc() {
    this.setData({
      playState: true
    })

  },
  pauseFunc() {
    this.setData({
      playState: false
    })
  },


  //下一曲
  nextPlay() {
    if (this.data.audioList.length == 0) {
      return
    }
    if (this.data.audioWay == 1) {
      //随机
      console.log('随机', this.data.audioList.length)
      this.setData({
        idx: Math.floor(Math.random() * Math.round(this.data.audioList.length)) % this.data.audioList.length
      })

    } else if (this.data.audioWay == 0) {
      //顺序
      console.log('顺序')
      if (this.data.idx >= (this.data.audioList.length - 1)) {
        this.setData({
          idx: 0
        })
      } else {
        this.setData({
          idx: this.data.idx + 1
        })

      }
    }//单曲循环
    this.audioInit1();
  },

  //上一曲
  upPlay() {
    if (this.data.audioList.length == 0) {
      return
    }
    if (this.data.audioWay == 1) {
      //随机
      console.log('随机');
      this.setData({
        idx: Math.floor(Math.random() * 10) % this.data.audioList.length
      })

    } else if (this.data.audioWay == 0) {
      //顺序
      console.log('顺序')
      if (this.data.idx < 1) {
        this.setData({
          idx: this.data.audioList.length - 1
        })

      } else {
        this.setData({
          idx: this.data.idx - 1
        })

      }
    }//单曲循环
    this.audioInit1()
  },


  

  //切换模式
  checkPlay(e) {
    if (this.data.audioWay > 1) {
      this.setData({
        audioWay: 0
      })

    } else {
      this.setData({
        audioWay: this.data.audioWay + 1
      })
    }

  },

  //获取音乐类型
  getMusicType() {
    api.fetchApi('music/index').then(res => {
      console.log(res)
      var musicType = res
      console.log(musicType)
      this.setData({
        musicType
      })
    })
  },

//筛选音乐类别
  chooseType(e){
    var id=e.currentTarget.dataset.id;
    var midx=e.currentTarget.dataset.midx;
    this.getMusicList(this.data.keywords, 1,id,0);
    this.setData({
      midx
    })
    // this.setData({
    //   isFocus: false
    // })
  },
 
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   // wx.getBackgroundAudioManager().stop();
    // bgAudioMannager = wx.getBackgroundAudioManager();
    // console.log(bgAudioMannager.src)
    this.setData({
      playState: app.globalData.playState1 || 0
    })
    let item = wx.getStorageSync('nowMusic1');
    let bgAudioMannager = wx.getBackgroundAudioManager();
    // if (wx.getStorageSync('nowMusic1'))
    if (bgAudioMannager.src == wx.getStorageSync('nowMusic1').src) {
      console.log('继续播放', bgAudioMannager);

      this.nonitor();
    } else {
      if (wx.getStorageSync('nowMusic1') && !wx.getStorageSync('nowMusic')) {
        bgAudioMannager.title = item.name;
        bgAudioMannager.singer = item.singer;
        bgAudioMannager.coverImgUrl = item.cover;
        bgAudioMannager.src = item.src;
        this.nonitor();
      }

    }

    this.getMusicType();
    this.getMusicList('',1,null,0);
   
   // this.audioInit();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    app.globalData.playState1 = this.data.playState;
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var page = this.data.page || 1;
    page++;

    this.getMusicList(this.data.keywords,page,null,0)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})